package com.demo.service.impl;

import com.demo.dto.User;
import com.demo.model.Auth;
import com.demo.repository.UserRepo;
import com.demo.util.JwtUtil;
import lombok.AllArgsConstructor;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.security.auth.login.AccountNotFoundException;
import java.util.Optional;

@Service
@AllArgsConstructor
public class UserServiceImp {
    private final UserRepo userRepo;
    private final PasswordEncoder passwordEncoder;
    private final JwtUtil jwtUtil;

    public Auth login(String userName,String password) {
        Optional<User> userOptional = userRepo.findOptionalByUsername(userName);
        if(userOptional.isPresent()){
            User user = userOptional.get();
            boolean matches = passwordEncoder.matches(password, user.getPassword());
            if(matches){
                String accessToken = jwtUtil.createAccessToken(user);
                String refreshToken = jwtUtil.createRefreshToken(user);
                Auth auth = new Auth(accessToken, refreshToken);
                return auth;
            }else{
                throw new AccessDeniedException("用户名或密码错误");
            }
        }else{
            throw new AccessDeniedException(userName+"没找到");
        }
    }


    /**
     * 判断用户名是否存在
     *
     * @param username 用户名
     * @return 存在与否
     */
    public boolean isUsernameExisted(String username) {
        return userRepo.countByUsername(username) > 0;
    }

    /**
     * 判断电邮地址是否存在
     *
     * @param email 电邮地址
     * @return 存在与否
     */
    public boolean isEmailExisted(String email) {
        return userRepo.countByEmail(email) > 0;
    }

    /**
     * 判断手机号是否存在
     *
     * @param mobile 手机号
     * @return 存在与否
     */
    public boolean isMobileExisted(String mobile) {
        return userRepo.countByMobile(mobile) > 0;
    }
}
